package managers
{
	import core.Game;
	
	import flash.geom.Point;
	
	import objects.Alien;
	import objects.Bullet;
	import objects.Hero;
	
	import states.Play;

	public class CollisionManager
	{
		private var _play:Play;
		private var _p1:Point;
		private var _p2:Point;
		
		public function CollisionManager(play:Play)
		{
			this._play = play;
			
			_p1 = new Point();
			_p2 = new Point();

		}
		
		public function update(deltaSmall:Number):void
		{
			bulletsAndAliens();
			heroAndAliens();
		}
		
		public function destroy():void
		{
			_play = null;
			_p1 = null;
			_p2 = null;
		}
		
		private function bulletsAndAliens():void
		{
			var bullets:Vector.<Bullet> = _play.bulletManager.bullets;
			var aliens:Vector.<Alien> = _play.alienManager.aliens;
			var b:Bullet;
			var a:Alien;
			
			for (var i:int = bullets.length - 1; i >= 0; i--)
			{
				b = bullets[i];
				
				for (var j:int = aliens.length - 1; j >= 0; j--)
				{
					a = aliens[j];
					
					_p1.x = b.x;
					_p1.y = b.y;
					_p2.x = a.x;
					_p2.y = a.y;
					
					if (Point.distance(_p1, _p2) < a.height * 0.5 + b.height * 0.5)
					{
						if (b.bounds.intersects(a.bounds))
						{
							_play.explosionManager.spawn(a.x, a.y);
							_play.bulletManager.destroyBullet(b, i);
							_play.alienManager.destroyAlien(a, j);
							_play.score.addScore(200);
						}
					}
				}
			}
		}
		
		private function heroAndAliens():void
		{
			var aliens:Vector.<Alien> = _play.alienManager.aliens;
			var a:Alien;
			var h:Hero = _play.hero;
			
			for (var j:int = aliens.length - 1; j >= 0; j--)
			{
				a = aliens[j];
				
				_p1.x = h.x;
				_p1.y = h.y;
				_p2.x = a.x;
				_p2.y = a.y;
				
				if (Point.distance(_p1, _p2) < (a.height * 0.5 + h.height * 0.5))
				{
					if (h.bounds.intersects(a.bounds))
					{
						trace("Player Dead");
						_play.alienManager.destroyAlien(a, j);
						_play.game.switchState(Game.GAME_OVER_STATE);
						break;
					}
				}
			}
		}
	}
}



































